const cell_width = 40;
const cell_height = 40;
const cell_margin = 50;
//用来计算延迟毫秒数的
let ci = 0; 
//存储数组
let rows = []; 
let timers = [];

//输入参数，并显示
function inNum(){
	let val = document.getElementById("inNum");
	rows.push({title:parseInt(val.value),flag:0});
	val.value = "";
	showItem();
}
//展示
function show(){
	sort_div = document.getElementById("sort_div");
	sort_div.innerHTML = ''; //清空所有元素
	for(var i = 0; i < rows.length; i++){
		let item = document.createElement('div');
		item.textContent = rows[i].title;
		item.style.position = 'absolute';
		item.style.textAlign = 'center';
		item.style.borderRadius = '50%';
		item.style.width = cell_width + 'px';
		item.style.height = cell_height + 'px';
		item.style.marginTop = rows[i].x + 'px';
		item.style.marginLeft = rows[i].y + 'px';
		item.style.border = rows[i].flag == 0 ? '1px solid #000': '1px solid red';
		sort_div.appendChild(item);
	}
}
//随机数字，进行排序
function startNum(){
	clear();
	// 生成随机数组 
	for(let i = 0; i < 5; i++){
		rows.push({title:Math.floor(Math.random() * 100),flag:0});
	}
	start();
    //const array = Array.from({ length: 5 }, () => Math.floor(Math.random() * 100));  
}
//清楚所有元素
function clear(){
	rows = [];
	ci = 0;
	// 清除所有setTimeout
	timers.forEach(function (timer) {
	  clearTimeout(timer);
	});
	//清除定时任务数组
	timers=[];
	show();
}
// 选中的颜色
function showSelectRed(row){
	showSelect(row,1);
}
// 去除选择的颜色
function showSelectUnRed(row){
	showSelect(row,0);
}
function showSelect(row,flag){
	setTimeout(()=>{
		for(let i = 0; i < rows.length; i++){
			rows[i].flag = 0;
		}
		row.flag = flag;
		show();
	},ci*200);
}
//开始插入动画
function start(){
	if(rows.length <2 ){
		alert("排序数据至少需要两个元素");
		return;
	}
	showItem();
	for(let i = 1; i < rows.length; i++){
		let row = rows[i];
		let j = i - 1;
		timeoutShow(row,'t'); //向上移动一个位置
		timeoutShow(row,'l'); //向左移动一个位置
		while(j >= 0 && rows[j].title > row.title){
			rows[j+1] = rows[j];
			showSelectRed(rows[j]);
			timeoutShow(rows[j],'r'); //向右移动一个位置
			showSelectUnRed(rows[j]);
			j -= 1;
			if(j >= 0){
				timeoutShow(row,'l'); //向左移动一个位置
			}
		}
		if(j >= 0){
			timeoutShow(row,'r'); //向右移动一个位置
		}
		rows[j+1] = row;
		timeoutShow(row,'b'); //向下移动一个位置
		//setTimeout(()=>{showItem();},ci*200);
	}
}
//位置重置
function showItem(){
	for(let i = 0; i < rows.length; i++){
		let row = rows[i];
		row.x = cell_margin;
		row.y = 10 + cell_margin * i;
	}
	show();
}
function timeoutShow(row,direction){
	for(let i = 0; i < 10; i++){
		timers.push(setTimeout(()=>{
			if(direction == 't'){
				row.x -= 5; //向上移动
			}else if(direction == 'b'){
				row.x += 5; //向下移动
			}if(direction == 'l'){
				row.y -= 5;  //向左移动
			}if(direction == 'r'){
				row.y += 5;  //向右移动
			}
			show();
		},200*ci));
		ci++;
	}
}